<template>
  <section>
    <h2>
      正在进行 <span id="todocount">{{ todoNum }}</span>
    </h2>
    <ol id="todolist" class="demo-box"></ol>
    <li v-for="todo in CountNum" :key="todo.id">
      <input
        type="checkbox"
        :checked="todo.done"
        @change="handleCheck(todo.id)"
      />
      <p @click="handleEdit(todo)" v-show="!todo.isEdit">{{ todo.title }}</p>
      <input
        class="edit"
        type="text"
        v-show="todo.isEdit"
        :value="todo.title"
        @blur="handleBlur(todo, $event)"
      />
      <a href="javascript:;" @click="handleDelete(todo.id)"></a>
    </li>
  </section>
</template>

<script>
export default {
  name: "TodoList",
  // data() {
  //   return {
  //     isEdit: false,
  //   };
  // },
  props: ["todos", "checkTodo", "deleteTodo"],
  methods: {
    //勾选
    handleCheck(id) {
      this.checkTodo(id);
    },
    //删除
    handleDelete(id) {
      if (confirm("确定删除吗")) {
        this.deleteTodo(id);
      }
    },
    //编辑
    handleEdit(todo) {
      if (todo.hasOwnProperty("isEdit")) {
        todo.isEdit = true;
      } else {
        this.$set(todo, "isEdit", true);
      }
      // this.$nextTick(() => {
      //   this.$refs.inputFocusp.focus();
      // });
      // setTimeout(() => {
      //   this.$refs.inputFocus.focus();
      // }, 200);
    },
    //失去焦点
    handleBlur(todo, e) {
      todo.isEdit = false;
      if (!e.target.value.trim()) return alert("输入不能为空");
      this.$bus.$emit("updataTodo", todo.id, e.target.value);
    },
  },
  computed: {
    todoNum() {
      return this.todos.reduce((pre, todo) => pre + (!todo.done ? 1 : 0), 0);
    },
    CountNum() {
      return this.todos.filter((todo) => !todo.done);
    },
  },
};
</script>

<style scoped>
.edit {
  margin-left: 40px;
  margin-top: -2px;
  width: 450px;
  height: 26px;
}
h2 {
  position: relative;
}
p {
  display: block;
  padding: 0 50px;
}
span {
  position: absolute;
  top: 2px;
  right: 5px;
  display: inline-block;
  padding: 0 5px;
  height: 20px;
  border-radius: 20px;
  background: #e6e6fa;
  line-height: 22px;
  text-align: center;
  color: #666;
  font-size: 14px;
}
ol,
li {
  padding: 0;
  list-style: none;
}
.edit {
  display: block;
}
</style>